package com.fate.securecheckplatform.ui.acts;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.fate.securecheckplatform.R;
import com.fate.securecheckplatform.base.BaseActivity;
import com.fate.securecheckplatform.bean.TableForbiddenPerformance;
import com.fate.securecheckplatform.constant.Constant;
import com.fate.securecheckplatform.ui.bprint.BluetoothDeviceList;
import com.fate.securecheckplatform.ui.bprint.DeviceConnFactoryManager;
import com.fate.securecheckplatform.ui.bprint.PrinterCommand;
import com.fate.securecheckplatform.utils.ExecutorManager;
import com.fate.securecheckplatform.utils.SpUtil;
import com.fate.securecheckplatform.utils.ToastUtil;
import com.google.gson.GsonBuilder;
import com.printer.command.EscCommand;
import com.printer.command.LabelCommand;

import java.util.Vector;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 我的打印功能
 */
public class MyPrintActivity extends BaseActivity {
    private static final int CONN_MOST_DEVICES = 0x11;
    private static final int CONN_PRINTER = 0x12;
    @BindView(R.id.tv_login_name)
    TextView mTvLoginName;
    @BindView(R.id.web_view)
    WebView mWebView;
    private String url;
    TableForbiddenPerformance performance;
    private boolean toPrint = false;
    private boolean pageFinished = false;
    private int id = 0;//

    /**
     * 使用打印机指令错误
     */
    private static final int PRINTER_COMMAND_ERROR = 0x008;

    /**
     * 连接状态断开
     */
    private static final int CONN_STATE_DISCONN = 0x007;

    @Override
    protected int layoutResId() {
        return R.layout.activity_my_print;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONN_STATE_DISCONN:
                    if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getConnState()) {
                        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
                        ToastUtil.toast(getString(R.string.str_disconnect_success));
                    }
                    break;
                case PRINTER_COMMAND_ERROR:
                    ToastUtil.toast(getString(R.string.str_choice_printer_command));
                    break;
                case CONN_PRINTER:
                    ToastUtil.toast(getString(R.string.str_cann_printer));
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void initData() {


    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter(Constant.ACTION_USB_PERMISSION);
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);
        registerReceiver(receiver, filter);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void initView() {
        performance = (TableForbiddenPerformance) getIntent().getSerializableExtra(Constant.DATA_PRINT);
        url = "file:////android_asset/print_table.html";
        String loginName = SpUtil.getInstance().getString(Constant.LOGIN_NAME);
        mTvLoginName.setText(TextUtils.isEmpty(loginName) ? "" : loginName);

        mWebView.getSettings().setJavaScriptEnabled(true);

        //设置自适应屏幕，两者合用
        mWebView.getSettings().setUseWideViewPort(true); //将图片调整到适合webview的大小
        mWebView.getSettings().setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                String content = new GsonBuilder().create().toJson(performance);
                mWebView.loadUrl("javascript:fillData(" + content + ")");
                pageFinished = true;
                if (toPrint) {
                    createWebPrintJob(view);
                }
            }
        });

        mWebView.loadUrl(url);
    }


    /**
     * wifi 打印任务
     *
     * @param webView
     */
    private void createWebPrintJob(WebView webView) {


        PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);


        PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();


        String jobName = getString(R.string.app_name) + " Document";

        PrintJob printJob = printManager.print(jobName, printAdapter,
                new PrintAttributes.Builder().build());

    }


    @OnClick({R.id.fl_a4, R.id.fl_tick, R.id.iv_back})
    public void onClickEvent(View view) {
        switch (view.getId()) {

            case R.id.fl_a4:
                toPrint = true;
                createWebPrintJob(mWebView);
                break;
            case R.id.fl_tick:
                printTicket();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * 打印小票
     */
    private void printTicket() {
        startActivityForResult(new Intent(this, BluetoothDeviceList.class),
                Constant.BLUETOOTH_REQUEST_CODE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                /*蓝牙连接*/
                case Constant.BLUETOOTH_REQUEST_CODE: {

                    closeport();
                    /*获取蓝牙mac地址*/
                    String macAddress = data.getStringExtra(BluetoothDeviceList.EXTRA_DEVICE_ADDRESS);
                    Log.e("--->", "--" + macAddress);
                    /* 初始化话DeviceConnFactoryManager */
                    new DeviceConnFactoryManager.Build()
                            .setId(id)
                            /* 设置连接方式 */
                            .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.BLUETOOTH)
                            /* 设置连接的蓝牙mac地址 */
                            .setMacAddress(macAddress)
                            .build();
                    /* 打开端口 */
                    ExecutorManager.getService().submit(() -> DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort());


                    break;
                }

                case CONN_MOST_DEVICES:
                    id = data.getIntExtra("id", -1);
                    if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null &&
                            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getConnState()) {
                        ToastUtil.toast("-链接成功-");
                    } else {
                        ToastUtil.toast("-链接失败-");
                    }
                    break;
            }
        }
    }


    /**
     * 打印标签
     */
    public void btnLabelPrint(String str) {
        ExecutorManager.getService().submit(() -> {
            if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null ||
                    !DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getConnState()) {
                mHandler.obtainMessage(CONN_PRINTER).sendToTarget();
                return;
            }
            if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getCurrentPrinterCommand() == PrinterCommand.TSC) {
                sendLabel(str);
            } else {
                mHandler.obtainMessage(PRINTER_COMMAND_ERROR).sendToTarget();
            }
        });
    }

    /**
     * 发送标签
     */
    void sendLabel(String content) {
        LabelCommand tsc = new LabelCommand();
        /* 设置标签尺寸，按照实际尺寸设置 */
        tsc.addSize(60, 40);

        /* 设置标签间隙，按照实际尺寸设置，如果为无间隙纸则设置为0 */
        tsc.addGap(4);
        /* 设置打印方向 */
        tsc.addDirection(LabelCommand.DIRECTION.BACKWARD,
                LabelCommand.MIRROR.NORMAL);
        /* 开启带Response的打印，用于连续打印 */
        tsc.addQueryPrinterStatus(LabelCommand.RESPONSE_MODE.OFF);
        /* 设置原点坐标 */
        tsc.addReference(0, 0);
        /* 撕纸模式开启 */
        tsc.addTear(EscCommand.ENABLE.ON);
        /* 清除打印缓冲区 */
        tsc.addCls();
        /* 绘制简体中文 */
        tsc.addText(130, 130, LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,
                LabelCommand.ROTATION.ROTATION_0,
                LabelCommand.FONTMUL.MUL_1,
                LabelCommand.FONTMUL.MUL_1,
                content);

        /* 打印标签 */
        tsc.addPrint(1);
        /* 打印标签后 蜂鸣器响 */
        tsc.addSound(2, 100);
        //        tsc.addOffset(12);
//        tsc.addCashdrwer(LabelCommand.FOOT.F5, 2, 2);
        Vector<Byte> datas = tsc.getCommand();
        /* 发送数据 */
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null) {
            Log.d("BLUE_PRINT", "sendLabel: 打印机为空");
            return;
        }
        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(datas);

    }

    private void closeport() {
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort != null) {
//            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].reader.cancel();
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort.closePort();
            DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].mPort = null;
        }
    }


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) return;
            switch (action) {
                case DeviceConnFactoryManager.ACTION_CONN_STATE:
                    int state = intent.getIntExtra(DeviceConnFactoryManager.STATE, -1);
                    int deviceId = intent.getIntExtra(DeviceConnFactoryManager.DEVICE_ID, -1);
                    switch (state) {
                        case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:
                            if (id == deviceId) {
                                ToastUtil.toast("未连接");
                            }
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTING:
                            ToastUtil.toast("正在连接...");
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                            ToastUtil.toast("连接成功");
                            // 真正的打印
                            if (performance != null) {
                                String czbh = performance.getCzbh();
                                String time = czbh.substring(0, 10);
                                String temp = czbh.substring(11);
                                btnLabelPrint(czbh);
                            }

                            break;
                        case DeviceConnFactoryManager.CONN_STATE_FAILED:
                            ToastUtil.toast("连接失败");
                            break;

                    }
                    break;

            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}
